package com.ctgu.rabbitmq.rabbitmq.exchange.topicExchange;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @ ClassName TopicExchangeConfig
 * @ Author Alex2
 * @ Date 2025/8/14 15:17
 **/
@Configuration
public class TopicExchangeConfig {

    public static final String TOPIC_EXCHANGE = "topic_exchange";
    public static final String QUEUE_USER = "queue_user";
    public static final String QUEUE_ORDER = "queue_order";

    // 路由键
    public static final String ROUTING_KEY_USER = "user.*";   // 匹配 user.开头的任意一个单词
    public static final String ROUTING_KEY_ORDER = "order.#"; // 匹配 order.开头的任意多个单词

    // 创建主题交换机
    @Bean(name = TOPIC_EXCHANGE)
    public TopicExchange topicExchange() {
        return new TopicExchange(TOPIC_EXCHANGE);
    }

    // 创建队列
    @Bean(name = QUEUE_USER)
    public Queue queueUser() {
        return new Queue(QUEUE_USER, true);
    }

    @Bean(name = QUEUE_ORDER)
    public Queue queueOrder() {
        return new Queue(QUEUE_ORDER, true);
    }

    // 绑定队列和交换机（带路由键）
    @Bean
    public Binding bindingQueueUser(
            @Qualifier(QUEUE_USER) Queue queue,
            @Qualifier(TOPIC_EXCHANGE) TopicExchange topicExchange) {
        return BindingBuilder.bind(queue).to(topicExchange).with(ROUTING_KEY_USER);
    }

    @Bean
    public Binding bindingQueueOrder(
            @Qualifier(QUEUE_ORDER) Queue queue,
            @Qualifier(TOPIC_EXCHANGE) TopicExchange topicExchange) {
        return BindingBuilder.bind(queue).to(topicExchange).with(ROUTING_KEY_ORDER);
    }
}
